library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity music_player is 
	port(clk : in std_logic;--1mhz
		--TN : in std_logic_vector(3 downto 0);--音符编码
		spks : out std_logic;
		clk_4hz:in std_logic;--0.25s per musical note
		--A : BUFFER STD_LOGIC_VECTOR(8 DOWNTO 0);
		state:IN INTEGER RANGE 0 TO 4
		);
end;

architecture rts of music_player is 
signal FM : std_logic;
signal count : integer range 0 to 2047;
signal temp : integer range 0 to 2048;
signal TN : integer range 0 to 15;--音符编码
signal count_note:integer range 0 to 19;
begin 
	
p1:	process (TN)
	begin

		case TN is
		when 0 => temp<=2048; 
		when 1 => temp<=1907;
		when 2 => temp<=1699;
		when 3 => temp<=1514;
		when 4=>temp<=1431;
		when 5 => temp<=1275;
		when 6 => temp<=1136;
		when 7 => temp<=1011;
		when 8 => temp<=955;-- 1+
		when 9 => temp<=851;-- 2+
		when 10 => temp<=758;-- 3+
		when 11=>temp<=715;-- 4+
		when 12 => temp<=637;-- 5+
		when 13 => temp<=567;-- 6+
		when 14 => temp<=505;-- 7+
		when 15 => temp<=477;-- 1++
		when others => temp<=2048;
		end case;
	end process;
	
p2:process(clk,temp)
	begin
	if(clk'event and clk='1') then count<=count+1;
		if(count=temp) then FM<=not FM;count<=0;end if;
	end if;
	end process;
	spks<=FM;

p3:PROCESS (clk_4hz)
	BEGIN
	IF (clk_4hz'event AND clk_4hz = '1') THEN
			IF(count_note=12) THEN 
				count_note<=0;
			ELSE 
				count_note<=count_note+1;
			END IF;
	END IF;
	END PROCESS;
	
P4:PROCESS(clk_4hz)
	BEGIN 
		IF (state=0) THEN
			CASE count_note IS
				WHEN 0=>TN<=10;
				WHEN 1=>TN<=9;
				WHEN 2=>TN<=4;
				WHEN 3=>TN<=4;
				WHEN 4=>TN<=5;
				WHEN 5=>TN<=5;
				WHEN 6=>TN<=9;
				WHEN 7=>TN<=8;
				WHEN 8=>TN<=3;
				WHEN 9=>TN<=1;
				WHEN 10=>TN<=3;
				WHEN 11=>TN<=5;
				WHEN 12=>TN<=8;
				WHEN 13=>TN<=8;
				WHEN 14=>TN<=8;
				WHEN 15=>TN<=8;
				WHEN 16=>TN<=7;
				WHEN 17=>TN<=6;
				WHEN 18=>TN<=0;
				WHEN 19=>TN<=0;
				
				
				
			END CASE;
		ELSE 
			TN<=0;
		END IF;
	END PROCESS;
				

end;
